﻿using fCloud.SensorApi.Services;

namespace fCloud.SensorApi;

public class CustomInitializer:IHostedService,IDisposable
{
    private Timer? _timer;
    private readonly ILogger<CustomInitializer> _logger;
    private readonly ITaskSchedulerService _taskSchedulerService;

    public CustomInitializer(IServiceScopeFactory scopeFactory)
    {
        var scope = scopeFactory.CreateScope();
        _logger=scope.ServiceProvider.GetRequiredService<ILogger<CustomInitializer>>();
        _taskSchedulerService=scope.ServiceProvider.GetRequiredService<ITaskSchedulerService>();
        
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("初始化");
        _timer = new Timer(ExcuteTask,null, TimeSpan.Zero, TimeSpan.FromSeconds(20));
        return Task.CompletedTask;
    }

    private void ExcuteTask(object? state)
    {
        _logger.LogInformation("执行后台任务");
        Task.Run(async () =>
        {
            //var res = await _taskSchedulerService.ScanSensorKeysAsync();
        });
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("执行服务关闭任务");
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
        GC.SuppressFinalize(this);
    }
}